import { useCallback, useEffect } from 'react';
import { Button, Checkbox, Col, Modal, Progress, Row, Tooltip } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { useI18n, getI18n } from '@vesoft-inc/i18n';
import { observer } from 'mobx-react-lite';
import { useHistory } from 'react-router-dom';
import type { History } from 'history';
import cls from 'classnames';
import { useStore } from '@app/stores';
import Icon from '@app/components/Icon';
import { trackPageView } from '@app/utils/stat';
import { useBatchState } from '@app/utils';
import styles from './index.module.less';

export interface ModuleItem {
  icon: string;
  title: string;
  tip: string;
  startLink: string;
  startDisabled?: boolean;
  disabledTip?: string;
  beta?: boolean;
  withOrder?: boolean;
}

const { intl } = getI18n();

export const getModuleList = (): ModuleItem[] => {
  return [
    {
      icon: 'icon-studio-nav-schema',
      title: intl.get('common.schema'),
      tip: intl.get('doc.schemaIntro'),
      startLink: '/schema',
    },
    {
      icon: 'icon-studio-nav-import',
      title: intl.get('import.importData'),
      tip: intl.get('doc.importIntro'),
      startLink: '/import/tasks',
    },
    {
      icon: 'icon-studio-nav-console',
      title: intl.get('common.console'),
      tip: intl.get('doc.consoleIntro'),
      startLink: '/console',
    },
    {
      icon: 'icon-navbar-sketch',
      title: intl.get('common.sketch'),
      tip: intl.get('doc.sketchIntro'),
      startLink: '/sketch',
    },
  ];
};

export type DatasetType = 'starter' | 'solution';


export const shouldAlwaysShowWelcome = () => localStorage.getItem('showWelcome') !== 'false';


const initLoadingTime = 21;

interface IProps {
  moduleList?: ModuleItem[];
  product?: string;
  onClosePage?: () => void;
}

// eslint-disable-next-line react-refresh/only-export-components
function Welcome(props: IProps) {
  const {
    moduleList = getModuleList(),
    // product = `${window.gConfig.databaseName} Studio`,
    onClosePage,
  } = props;
  const history = useHistory() as History;
  const { welcome } = useStore();
  const { intl } = useI18n();
  const { spaceLoading, setSpaceLoading } = welcome;
  const { state, setState } = useBatchState({
    actionShow: shouldAlwaysShowWelcome(),
  });
  const { actionShow } = state;


  const onShowPageCheckboxChange = useCallback((e: CheckboxChangeEvent) => {
    const actionShow = e.target.checked;
    setState({ actionShow });
    localStorage.setItem('showWelcome', `${actionShow}`);
  }, []);

  const closePageHandler = useCallback(() => {
    typeof onClosePage === 'function' ? onClosePage() : history.replace('/console');
  }, [onClosePage]);

  useEffect(() => {
    spaceLoading.spaceName && setSpaceLoading({ progressModalOpen: true });
    trackPageView('/welcome');
  }, []);


  // @ts-ignore
  const percent = (((initLoadingTime - spaceLoading?.leftTime) / initLoadingTime) * 100) | 0;
  const renderPercent = percent > 99 ? 99 : percent;

  return (
    <div className={styles.welcomeWrapper}>
      <div className={styles.welcomeHeader}>
        <div className={styles.headerAction}>
          <Checkbox checked={actionShow} onChange={onShowPageCheckboxChange}>
            {intl.get('welcome.alwaysShow')}
          </Checkbox>
          <Icon type="icon-studio-btn-close" className={styles.actionClose} onClick={closePageHandler} />
        </div>
        {/*<h1 className={styles.welcomeLabel}>*/}
        {/*  {intl.get('doc.welcome')}&nbsp;<span style={{ fontWeight: 'bold' }}>{product}</span>*/}
        {/*</h1>*/}
      </div>
      <div className={styles.docBox}>
        <div className={styles.header}>{intl.get('doc.functionIntro')}</div>
        <Row className={styles.moduleIntro} gutter={[26, 26]}>
          {moduleList.map((module, idx) => (
            <Col span={8} key={module.title}>
              <div className={styles.moduleItem}>
                <Icon type={module.icon} />
                <span className={cls(styles.title, module.beta && styles.beta)}>{module.title}</span>
                <span className={styles.tip}>{module.tip}</span>
                <div className={styles.actionWrapper}>
                  {module.disabledTip ? (
                    <Tooltip title={module.disabledTip}>
                      <Button
                        className={styles.disabledAction}
                        disabled={!!module.startDisabled}
                        type="primary"
                        onClick={() => history.push(module.startLink)}
                      >
                        {intl.get('welcome.quickStart')}
                      </Button>
                    </Tooltip>
                  ) : (
                    <Button
                      className={styles.action}
                      disabled={!!module.startDisabled}
                      type="primary"
                      onClick={() => history.push(module.startLink)}
                    >
                      {intl.get('welcome.quickStart')}
                    </Button>
                  )}

                </div>
                {module.withOrder && <div className={styles.order}>{idx + 1}</div>}
              </div>
            </Col>
          ))}
        </Row>
      </div>

      <Modal
        footer={null}
        maskClosable={false}
        width={640}
        title={spaceLoading.spaceName || ''}
        open={spaceLoading.progressModalOpen}
        onCancel={() => setSpaceLoading({ progressModalOpen: false })}
        closable={false}
      >
        <div className={styles.progressWrapper}>
          <div className={styles.title}>
            <span>{intl.get('welcome.progressTitle')}</span>
            <span>{`${renderPercent}%`}</span>
          </div>
          <div className={styles.content}>
            <Progress percent={renderPercent} showInfo={false} />
          </div>
        </div>
      </Modal>
    </div>
  );
}

// eslint-disable-next-line react-refresh/only-export-components
export default observer(Welcome);
